package net.miranti.client.view;

import net.miranti.client.EntryBean;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;

public class SelectorWidget<H> extends Composite {
	private boolean initiated;
	protected ListBox listbox = new ListBox(); 

	public SelectorWidget() { 
		initWidget(listbox);
	}
	
	public void addSelectionCommand(final Command command){
		listbox.addChangeHandler(new ChangeHandler() {
			@Override
			public void onChange(ChangeEvent event) {
				command.execute();
			}
		});
	}
	
	public EntryBean getSelection() {
		int index = listbox.getSelectedIndex();
		EntryBean res;
		if (index==0)
			res = EntryBean.EMPTY_KEY;
		else {
			Long id = new Long(listbox.getValue(index));
			String name = listbox.getItemText(index);
			res = new EntryBean(id, name);
		}
		return res; 
	}
	
	public void initOptions(EntryBean[] options) {
		listbox.clear();
		listbox.addItem("");
		for(EntryBean option : options)
			listbox.addItem(option.getValue().toString(), option.getKey().toString());
		initiated = true;
	}
	
	public void initOptions(EntryBean[] options, String selected) {
		initOptions(options);
		select(selected);
	}
	
	public void select(String selected) {
		int index = 0;
		if (selected!=null && !selected.isEmpty()) {
			int n = listbox.getItemCount();
			for (int i=1; i<n; i++) {
				if (selected.equals(listbox.getValue(i))) {
					index = i;
					break;
				}
			}
		}
		listbox.setSelectedIndex(index);
	}

	public boolean isInitiated() {
		return initiated;
	}
}